{% extends "base.html" %}
{% block title %}上传头像 - {{ current_user.real_name }} - 乒乓球培训管理系统{% endblock %}
{% block page_title %}上传头像{% endblock %}

{% block extra_css %}
<style>
.upload-container {
    background: white;
    border-radius: 20px;
    box-shadow: 0 15px 35px rgba(0,0,0,0.1);
    padding: 0;
    overflow: hidden;
    margin: 2rem auto;
    max-width: 800px;
}

.upload-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 2rem;
    text-align: center;
    position: relative;
}

.upload-header::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 200%;
    background: rgba(255,255,255,0.1);
    transform: rotate(45deg);
    pointer-events: none;
}

.upload-content {
    padding: 2rem;
}

.current-avatar-section {
    text-align: center;
    margin-bottom: 2rem;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 15px;
}

.current-avatar {
    width: 150px;
    height: 150px;
    object-fit: cover;
    border-radius: 50%;
    border: 5px solid #e9ecef;
    margin-bottom: 1rem;
}

.avatar-placeholder {
    width: 150px;
    height: 150px;
    background: #e9ecef;
    border: 5px solid #dee2e6;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6c757d;
    font-size: 4rem;
    margin: 0 auto 1rem;
}

.upload-area {
    border: 3px dashed #dee2e6;
    border-radius: 15px;
    padding: 3rem 2rem;
    text-align: center;
    background: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
    margin-bottom: 2rem;
    position: relative;
    overflow: hidden;
}

.upload-area:hover {
    border-color: #667eea;
    background: #e7f3ff;
    transform: scale(1.02);
}

.upload-area.dragover {
    border-color: #28a745;
    background: #d4edda;
    transform: scale(1.05);
}

.upload-icon {
    font-size: 4rem;
    color: #6c757d;
    margin-bottom: 1rem;
    transition: color 0.3s ease;
}

.upload-area:hover .upload-icon {
    color: #667eea;
}

.upload-text {
    font-size: 1.1rem;
    color: #495057;
    margin-bottom: 0.5rem;
}

.upload-hint {
    color: #6c757d;
    font-size: 0.9rem;
}

.preview-section {
    display: none;
    background: #f8f9fa;
    border-radius: 15px;
    padding: 2rem;
    margin-bottom: 2rem;
    text-align: center;
}

.preview-container {
    position: relative;
    display: inline-block;
    margin-bottom: 1rem;
}

.preview-image {
    max-width: 100%;
    max-height: 400px;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.crop-container {
    position: relative;
    max-width: 100%;
    margin: 0 auto;
}

.crop-controls {
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    margin-top: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.control-group {
    margin-bottom: 1rem;
}

.control-label {
    display: block;
    font-weight: 500;
    color: #495057;
    margin-bottom: 0.5rem;
}

.control-slider {
    width: 100%;
    height: 6px;
    border-radius: 3px;
    background: #e9ecef;
    outline: none;
    transition: background 0.3s ease;
}

.control-slider::-webkit-slider-thumb {
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #667eea;
    cursor: pointer;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.control-slider::-moz-range-thumb {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #667eea;
    cursor: pointer;
    border: none;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.btn-upload {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    padding: 0.875rem 2rem;
    border-radius: 12px;
    font-weight: 500;
    font-size: 1rem;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    min-width: 150px;
    justify-content: center;
}

.btn-upload:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
    color: white;
}

.btn-upload:disabled {
    opacity: 0.6;
    transform: none;
    box-shadow: none;
}

.action-buttons {
    display: flex;
    gap: 1rem;
    justify-content: center;
    flex-wrap: wrap;
}

.upload-progress {
    display: none;
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    margin-top: 1rem;
    text-align: center;
}

.progress-bar-container {
    background: #e9ecef;
    border-radius: 10px;
    height: 8px;
    overflow: hidden;
    margin: 1rem 0;
}

.progress-bar {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    height: 100%;
    border-radius: 10px;
    transition: width 0.3s ease;
    width: 0%;
}

.file-info {
    display: none;
    background: #e3f2fd;
    border: 1px solid #bbdefb;
    border-radius: 10px;
    padding: 1rem;
    margin-top: 1rem;
}

.file-info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
}

.file-info-item:last-child {
    margin-bottom: 0;
}

.error-message {
    background: #ffebee;
    border: 1px solid #ffcdd2;
    border-radius: 10px;
    padding: 1rem;
    margin-top: 1rem;
    color: #c62828;
    display: none;
}

@media (max-width: 768px) {
    .upload-container {
        margin: 1rem;
        border-radius: 15px;
    }

    .upload-header {
        padding: 1.5rem;
    }

    .upload-content {
        padding: 1.5rem;
    }

    .upload-area {
        padding: 2rem 1rem;
    }

    .current-avatar,
    .avatar-placeholder {
        width: 120px;
        height: 120px;
    }

    .action-buttons {
        flex-direction: column;
        align-items: stretch;
    }

    .btn-upload {
        width: 100%;
        margin-bottom: 0.5rem;
    }
}
</style>
<!-- Cropper.js CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 返回按钮 -->
    <div class="mb-3">
        <a href="{{ url_for('profile.view') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回个人资料
        </a>
    </div>

    <div class="upload-container">
        <div class="upload-header">
            <div class="d-flex align-items-center justify-content-center mb-3">
                <i class="bi bi-camera fs-1 me-3"></i>
                <div>
                    <h3 class="mb-1">上传头像</h3>
                    <p class="mb-0 opacity-75">选择一张图片作为您的头像</p>
                </div>
            </div>
        </div>

        <div class="upload-content">
            <!-- 当前头像 -->
            <div class="current-avatar-section">
                <h5 class="mb-3">当前头像</h5>
                {% if current_user.photo_url %}
                <img src="{{ current_user.photo_url }}" alt="当前头像" class="current-avatar">
                {% else %}
                <div class="avatar-placeholder">
                    <i class="bi bi-person-fill"></i>
                </div>
                {% endif %}
                <p class="text-muted mt-2">
                    {% if current_user.photo_url %}
                        上传新头像将替换当前头像
                    {% else %}
                        您还没有设置头像
                    {% endif %}
                </p>
            </div>

            <!-- 上传区域 -->
            <div class="upload-area" id="uploadArea">
                <i class="bi bi-cloud-upload upload-icon"></i>
                <div class="upload-text">点击选择图片或拖拽图片到此处</div>
                <div class="upload-hint">支持 JPG、PNG、GIF 格式，建议尺寸 300x300 像素，文件大小不超过 5MB</div>
                <input type="file" id="avatarInput" accept="image/*" style="display: none;">
            </div>

            <!-- 文件信息 -->
            <div class="file-info" id="fileInfo">
                <h6><i class="bi bi-info-circle me-2"></i>文件信息</h6>
                <div class="file-info-item">
                    <span>文件名：</span>
                    <span id="fileName">-</span>
                </div>
                <div class="file-info-item">
                    <span>文件大小：</span>
                    <span id="fileSize">-</span>
                </div>
                <div class="file-info-item">
                    <span>图片尺寸：</span>
                    <span id="imageDimensions">-</span>
                </div>
            </div>

            <!-- 错误消息 -->
            <div class="error-message" id="errorMessage">
                <i class="bi bi-exclamation-triangle me-2"></i>
                <span id="errorText"></span>
            </div>

            <!-- 预览和裁剪 -->
            <div class="preview-section" id="previewSection">
                <h5 class="mb-3">调整头像</h5>
                <div class="crop-container">
                    <img id="cropImage" class="preview-image">
                </div>

                <div class="crop-controls">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="control-group">
                                <label class="control-label">缩放</label>
                                <input type="range" class="control-slider" id="scaleSlider"
                                       min="0.1" max="3" step="0.1" value="1">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="control-group">
                                <label class="control-label">旋转</label>
                                <input type="range" class="control-slider" id="rotateSlider"
                                       min="-180" max="180" step="1" value="0">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="action-buttons">
                    <button type="button" class="btn-upload" id="uploadBtn">
                        <i class="bi bi-upload"></i>
                        上传头像
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="cancelBtn">
                        <i class="bi bi-x"></i>
                        取消
                    </button>
                    <button type="button" class="btn btn-outline-primary" id="resetBtn">
                        <i class="bi bi-arrow-clockwise"></i>
                        重置
                    </button>
                </div>
            </div>

            <!-- 上传进度 -->
            <div class="upload-progress" id="uploadProgress">
                <div class="d-flex align-items-center justify-content-center mb-2">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    <span>正在上传头像...</span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar" id="progressBar"></div>
                </div>
                <small class="text-muted">请稍候，正在处理您的头像</small>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- Cropper.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
<script>
let cropper = null;
let currentFile = null;

// 文件大小格式化
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示错误消息
function showError(message) {
    const errorDiv = document.getElementById('errorMessage');
    const errorText = document.getElementById('errorText');
    errorText.textContent = message;
    errorDiv.style.display = 'block';

    setTimeout(() => {
        errorDiv.style.display = 'none';
    }, 5000);
}

// 隐藏错误消息
function hideError() {
    document.getElementById('errorMessage').style.display = 'none';
}

// 验证文件
function validateFile(file) {
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
        return '请选择 JPG、PNG 或 GIF 格式的图片';
    }

    // 检查文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
        return '图片大小不能超过 5MB';
    }

    return null;
}

// 处理文件选择
function handleFileSelect(file) {
    hideError();

    // 验证文件
    const error = validateFile(file);
    if (error) {
        showError(error);
        return;
    }

    currentFile = file;

    // 显示文件信息
    const fileInfo = document.getElementById('fileInfo');
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = formatFileSize(file.size);
    fileInfo.style.display = 'block';

    // 读取图片
    const reader = new FileReader();
    reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
            // 更新图片尺寸信息
            document.getElementById('imageDimensions').textContent = `${this.width} x ${this.height}`;

            // 显示预览和裁剪
            showPreview(e.target.result);
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

// 显示预览和裁剪界面
function showPreview(imageSrc) {
    const previewSection = document.getElementById('previewSection');
    const cropImage = document.getElementById('cropImage');

    cropImage.src = imageSrc;
    previewSection.style.display = 'block';

    // 销毁现有的cropper
    if (cropper) {
        cropper.destroy();
    }

    // 初始化cropper
    cropper = new Cropper(cropImage, {
        aspectRatio: 1, // 正方形
        viewMode: 2,
        preview: '.preview',
        responsive: true,
        restore: false,
        guides: true,
        center: true,
        highlight: false,
        cropBoxMovable: true,
        cropBoxResizable: true,
        toggleDragModeOnDblclick: false,
    });

    // 绑定控制器事件
    bindCropControls();
}

// 绑定裁剪控制器
function bindCropControls() {
    const scaleSlider = document.getElementById('scaleSlider');
    const rotateSlider = document.getElementById('rotateSlider');

    scaleSlider.addEventListener('input', function() {
        if (cropper) {
            cropper.scale(parseFloat(this.value));
        }
    });

    rotateSlider.addEventListener('input', function() {
        if (cropper) {
            cropper.rotateTo(parseFloat(this.value));
        }
    });
}

// 重置裁剪
function resetCrop() {
    if (cropper) {
        cropper.reset();
        document.getElementById('scaleSlider').value = 1;
        document.getElementById('rotateSlider').value = 0;
    }
}

// 取消上传
function cancelUpload() {
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }

    currentFile = null;
    document.getElementById('previewSection').style.display = 'none';
    document.getElementById('fileInfo').style.display = 'none';
    document.getElementById('avatarInput').value = '';
    hideError();
}

// 上传头像
function uploadAvatar() {
    if (!cropper || !currentFile) {
        showError('请先选择并调整图片');
        return;
    }

    // 显示上传进度
    const uploadProgress = document.getElementById('uploadProgress');
    const progressBar = document.getElementById('progressBar');
    uploadProgress.style.display = 'block';

    // 获取裁剪后的canvas
    const canvas = cropper.getCroppedCanvas({
        width: 300,
        height: 300,
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high'
    });

    // 转换为blob
    canvas.toBlob(function(blob) {
        const formData = new FormData();
        formData.append('avatar', blob, 'avatar.jpg');

        // 获取裁剪参数
        const cropData = cropper.getData();
        formData.append('crop_x', Math.round(cropData.x));
        formData.append('crop_y', Math.round(cropData.y));
        formData.append('crop_width', Math.round(cropData.width));
        formData.append('crop_height', Math.round(cropData.height));

        // 添加CSRF token
        const csrfToken = document.querySelector('meta[name=csrf-token]');
        if (csrfToken) {
            formData.append('csrf_token', csrfToken.getAttribute('content'));
        }

        // 发送请求
        fetch('{{ url_for("profile.api_avatar_upload") }}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            uploadProgress.style.display = 'none';

            if (data.success) {
                // 上传成功
                alert('头像上传成功！');
                window.location.href = '{{ url_for("profile.view") }}';
            } else {
                showError(data.error || '上传失败，请重试');
            }
        })
        .catch(error => {
            uploadProgress.style.display = 'none';
            showError('上传失败：' + error.message);
        });

        // 模拟进度条
        let progress = 0;
        const progressInterval = setInterval(() => {
            progress += Math.random() * 30;
            if (progress > 95) progress = 95;
            progressBar.style.width = progress + '%';

            if (progress >= 95) {
                clearInterval(progressInterval);
            }
        }, 200);

    }, 'image/jpeg', 0.9);
}

// 初始化事件监听
document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('uploadArea');
    const avatarInput = document.getElementById('avatarInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const resetBtn = document.getElementById('resetBtn');

    // 点击上传区域
    uploadArea.addEventListener('click', function() {
        avatarInput.click();
    });

    // 文件选择
    avatarInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            handleFileSelect(e.target.files[0]);
        }
    });

    // 拖拽上传
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');

        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });

    // 按钮事件
    uploadBtn.addEventListener('click', uploadAvatar);
    cancelBtn.addEventListener('click', cancelUpload);
    resetBtn.addEventListener('click', resetCrop);
});
</script>
{% endblock %}